package uno.linze.wallpaper.domain.identity.service.ext;

// VerifyCodeService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;
import java.util.Random;
@Service
public class VerifyCodeService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender mailSender;

    public void sendAndSaveCode(String email, long timeoutMinutes) throws MessagingException {
        String code = String.valueOf(new Random().nextInt(900000) + 100000); // 6位验证码
        redisTemplate.opsForValue().set(email, code, timeoutMinutes, TimeUnit.MINUTES);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("2623232979@qq.com"); // 设置发送地址，必须与SMTP认证用户一致
        helper.setTo(email);
        helper.setSubject("注册验证码");
        String html = String.format("""
    <div style="font-family:Arial,sans-serif;padding:24px;background:#f9f9f9;border-radius:8px;width:360px;margin:auto;">
        <h2 style="color:#4CAF50;">注册验证码</h2>
        <p>您好，</p>
        <p>您的验证码是：</p>
        <div style="font-size:32px;font-weight:bold;color:#2196F3;padding:12px 0;">%s</div>
        <p>有效期 <b>%d</b> 分钟，请尽快使用。</p>
        <hr style="border:none;border-top:1px solid #eee;margin:24px 0;">
        <small style="color:#888;">如果不是您本人操作，请忽略此邮件。</small>
    </div>
    """, code, timeoutMinutes);
        helper.setText(html, true);
        mailSender.send(message);
    }

    /**
     * 检查验证码是否正确。
     * @param email 邮箱地址
     * @param code  用户提供的验证码
     * @return 如果验证码正确则返回 true，否则返回 false
     */
    public boolean checkCode(String email, String code) {
        String storedCode = redisTemplate.opsForValue().get(email);
        return code != null && code.equals(storedCode);
    }
}